package cn.com.dhcc.app.pub.module.login.service;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;

import org.springframework.util.StringUtils;

import cn.com.dhcc.app.core.base.user.LoginUser;
import cn.com.dhcc.app.core.para.CorePara.StaticPara;
import cn.com.dhcc.app.pub.core.AppPara.UAMS;
/**
 * 用来验证是否绕过单点
 * @author qiao
 * @2014-3-18 @下午1:48:25
 */
public class IngoreSso {

	public static String ingnoreUrl="";
	public static boolean ignore(ServletRequest request){
		//1 非单点登录
		if(!UAMS.SSO_ENABLED)return true;
		
		//2 在ignore列表里
		HttpServletRequest httpServletRequest = (HttpServletRequest)request;
		ingnoreUrl = httpServletRequest.getSession().getServletContext().getInitParameter("ssoIngoreUri");
		if(isIgnoreUrl(httpServletRequest))return true;
		
		//3流域和省对中央支撑软件的请求也要绕过单点
		if(isThirdAppRequest(httpServletRequest))return true;
		LoginUser sessionVo = (LoginUser) httpServletRequest.getSession().getAttribute(StaticPara.USER_SESSION_KEY);
		
		//4超级管理员绕过单点
		if(sessionVo==null)return false;
		if(sessionVo!=null&&sessionVo.isSuperAdmin())return true;
		
		return false;
	}
	  //如果请求里面有相关标识（加密的key）此key在登陆后发给流域和省，在以后的每次请求中需要跟在请求后面
	  public static boolean isThirdAppRequest(HttpServletRequest request){
		  Object token = request.getSession().getAttribute(StaticPara.USER_SESSION_TOKEN_KEY);
		  if(token==null)return false;
		  String tokenStr = String.valueOf(token);
		  if(!StringUtils.hasText(tokenStr)&&tokenStr.length()!=32){
			  return false;
		  }
		  return true;
	  }
	  public static boolean isIgnoreUrl(HttpServletRequest httpServletRequest){
		  String uri = httpServletRequest.getRequestURI();
		  if(StringUtils.hasText(uri)&&StringUtils.hasText(ingnoreUrl)){
			  String[] ignoreUrls =ingnoreUrl.split(",");
			  for (int i = 0; i < ignoreUrls.length; i++) {
				  if(StringUtils.hasText(uri)&&uri.endsWith(ignoreUrls[i])){
					  return true;
				  }
			}
		  }
		  return false;
	    }
}
